import { Icon, Input } from "antd";
import React, { useEffect, useRef } from "react";
import './InputQuickEditor.less'
type InputQuickEditorProps = {
    children?: any,
    style?:any,
    value:any, 
    onUpdate?:(value:any)=>void
}
const InputQuickEditor = ( props:InputQuickEditorProps )=>{
    const [isEditing, setIsEditing] = React.useState(false);
    const [value, setValue] = React.useState(props.value);
    const refInput = useRef(null);
    useEffect(()=>{
        setValue(props.value)
    },[props])
    useEffect(()=>{
      if(!isEditing){
        return;
      }
      refInput.current.focus()
    },[isEditing])
    const createDefaultChild = ()=>{
      return <Input ref={refInput} size='small' value={value} onChange={(e)=>{
        setValue(e.target.value)
      }} 
      onBlur={(e)=>{
        const newValue = e.target.value;
        if( props.onUpdate ){
          console.log("onUpdate", newValue)
          setValue(newValue)
          props.onUpdate(newValue)  
        }
        setIsEditing(false)
      }}
      onPressEnter={(e)=>{
        const newValue = (e.target as any).value;
        if( props.onUpdate ){
          setValue(newValue)
          props.onUpdate(newValue)  
        }
        setIsEditing(false)
      }}
      ></Input>
    }
    return (
        <div className="input-quick-editor" style={props.style}>
            {
                isEditing
                    ? createDefaultChild()
                    : <>{props.children||''}<span onClick={() => { setIsEditing(true) }}><Icon type="edit" /></span></>
            }
        </div>
    )
}

export default InputQuickEditor;
